<script setup>
import { onMounted, ref } from "vue";
//导入dept.js
import {
  getDeptList,
  queryDeptById,
  saveDept,
  updateDept,
  deleteById,
} from "@/api/dept";
import { ElMessage, ElMessageBox } from "element-plus";

let deptList = ref([]);

// 新增：获取表单引用
const formRef = ref(null);
const dialogVisible = ref(false);
const deptForm = ref({
  name: "",
});

//对话框标题
const formTitle = ref("");

//删除部门,命名为handleDelete
const handleDelete = (id) => {
  //删除部门时, 需要弹出一个确认框, 如果是确认, 则删除部门
  ElMessageBox.confirm("此操作将永久删除该部门, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 删除部门
    const result = await deleteById(id);
    if (result.code) {
      ElMessage.success("删除成功");
      list();
    }
  });
};

//编辑部门-根据id回显部门
const handleEdit = async (id) => {
  formTitle.value = "修改部门";
  dialogVisible.value = true;
  const result = await queryDeptById(id);
  if (result.code === 1) {
    deptForm.value = result.data;
  }
};

// 定义日期格式化方法
const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
};

// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
});

// 打开新增对话框
const openDialog = () => {
  formTitle.value = "新增部门";
  deptForm.value = {};
  formRef.value?.resetFields();
  dialogVisible.value = true;
};

//表单验证
const submitForm = async () => {
  await formRef.value.validate();
  let res = null;
  if (deptForm.value.id) {
    res = await updateDept(deptForm.value);
  } else {
    res = await saveDept(deptForm.value);
  }
  // 「新增验证」
  // ...原有提交逻辑
  if (res.code === 1) {
    ElMessage.success("保存成功");
    dialogVisible.value = false;
    list();
  } else {
    ElMessage.error(res.message);
  }
};

const list = async () => {
  const res = await getDeptList();
  if (res.code === 1) {
    deptList.value = res.data;
  } else {
    // 提示错误信息
    ElMessage.error(res.message);
  }
};
onMounted(() => {
  list();
});
</script>

<template>
  <h3>部门管理</h3>
  <el-button type="primary" size="large" class="but" @click="openDialog()"
    >新增部门
  </el-button>

  <el-table :data="deptList" border style="width: 100%">
    <el-table-column type="index" label="序号" width="80" align="center" />
    <el-table-column prop="name" label="部门名称" width="280" align="center" />
    <el-table-column
      prop="updateTime"
      label="最后操作时间"
      width="380"
      align="center"
    >
      <template #default="scope">
        {{ formatDate(scope.row.updateTime) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="success" @click="handleEdit(scope.row.id)"
          >编辑
        </el-button>
        <el-button type="danger" @click="handleDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
    >
  </el-table>

  <!-- 新增或者编辑部门对话框 -->
  <el-dialog
    v-if="dialogVisible"
    v-model="dialogVisible"
    :title="formTitle"
    width="500px"
    @closed="formRef?.resetFields()"
  >
    <el-form ref="formRef" :model="deptForm" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="deptForm.name"
          placeholder="请输入部门名称，长度为2-10位"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
h3 {
  margin: 0 0 20px 0;
}

.but {
  width: 100px;
  margin: 0 0 10px 0;
}
</style>
